package com.ahaoyou.init;

import com.ahaoyou.job.task.TestJob;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author LH
 * @version 1.0
 * @date 2022/9/18 18:24
 */
@Slf4j
@Component
public class Init implements CommandLineRunner {
    public static AtomicInteger count = new AtomicInteger(0);
    private static String TRIGGER_GROUP_NAME = "test_trriger";
    private static String JOB_GROUP_NAME = "test_job";
    @Autowired
    private Scheduler scheduler;

    @Override
    public void run(String... args) throws Exception {
        TriggerKey triggerKey = TriggerKey.triggerKey("trigger1", TRIGGER_GROUP_NAME);
        CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
        if (null == trigger) {
            Class clazz = TestJob.class;
            JobDetail jobDetail = JobBuilder.newJob(clazz).withIdentity("job1", JOB_GROUP_NAME).build();
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule("0/10 * * * * ?");
            trigger = TriggerBuilder.newTrigger().withIdentity("trigger1", TRIGGER_GROUP_NAME)
                    .withSchedule(scheduleBuilder).build();
            scheduler.scheduleJob(jobDetail, trigger);
            log.info("Quartz 创建了job:...:{}", jobDetail.getKey());
        } else {
            log.info("job已存在:{}", trigger.getKey());
        }
        TriggerKey triggerKey2 = TriggerKey.triggerKey("trigger2", TRIGGER_GROUP_NAME);
        CronTrigger trigger2 = (CronTrigger) scheduler.getTrigger(triggerKey2);
        if (null == trigger2) {
            Class clazz = TestJob.class;
            JobDetail jobDetail2 = JobBuilder.newJob(clazz).withIdentity("job2", JOB_GROUP_NAME).build();
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule("0/15 * * * * ?");
            trigger2 = TriggerBuilder.newTrigger().withIdentity("trigger2", TRIGGER_GROUP_NAME)
                    .withSchedule(scheduleBuilder).build();
            scheduler.scheduleJob(jobDetail2, trigger2);
            log.info("Quartz 创建了job:...:{}", jobDetail2.getKey());
        } else {
            log.info("job已存在:{}", trigger2.getKey());
        }
    }
}